package cc.eddic.practice.spring.webapi;

import cc.eddic.practice.spring.domain.SubCategory;
import cc.eddic.practice.spring.dto.CategoryAddRequest;
import cc.eddic.practice.spring.dto.CategoryResponse;
import cc.eddic.practice.spring.dto.SubCategoryAddRequest;
import cc.eddic.practice.spring.dto.SubCategoryResponse;
import cc.eddic.practice.spring.repository.CategoryRepository;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import javax.transaction.Transactional;
import java.util.Comparator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/api/categories")
public class CategoryRestController {
    private final CategoryRepository repository;
    private final CategoryRepository categoryRepository;

    public CategoryRestController(CategoryRepository repository, CategoryRepository categoryRepository) {
        this.repository = repository;
        this.categoryRepository = categoryRepository;
    }
    @PostMapping
    public HttpEntity<?> add(@RequestBody final CategoryAddRequest model){
        val category=repository.save(model.as());
        return ResponseEntity.created(ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(category.getId()).toUri()).build();
    }
    @DeleteMapping("/{id}")
    public HttpEntity<?> del(@PathVariable("id") final long id){
        repository.deleteById(id);
        return ResponseEntity.noContent().build();
    }
    @GetMapping("/{id}")
    public HttpEntity<CategoryResponse> get(@PathVariable("id") final long id){
        if (log.isDebugEnabled()) log.debug("id={}",id);
        val category=repository.findById(id).orElseThrow(NoSuchElementException::new);
        return ResponseEntity.ok(CategoryResponse.from(category));
    }
    @Transactional
    @PostMapping("/{categoryId}/subcategories")
    public HttpEntity<?> add(@PathVariable("categoryId") Long categoryId, @RequestBody final SubCategoryAddRequest model){
        val category= categoryRepository.findById(categoryId).orElseThrow(NoSuchElementException::new);
        val subCategory = model.as();
        category.add(subCategory);
        categoryRepository.save(category);
        val id=category.getSubCategories().stream()
                .filter(x->x.getName().equals(model.getName()))
                .sorted(Comparator.comparing(SubCategory::getCreatedOn).reversed())
                .map(SubCategory::getId)
                .findFirst().orElse(-1L);
    return ResponseEntity.created(ServletUriComponentsBuilder.fromCurrentRequest().path("/{subCategoryId}")
            .buildAndExpand(id).toUri()).build();
//    return ResponseEntity.ok().build();
    }
    @GetMapping("/{categoryId}/subcategories")
    public HttpEntity<?> get(@PathVariable ("categoryId") Long categoryId){
        if (log.isDebugEnabled()) log.debug("ca tegoryId = {}",categoryId);
        val category = categoryRepository.findById(categoryId).orElseThrow(NoSuchElementException::new);
        if (log.isDebugEnabled()) log.debug("run lazy load");
        return ResponseEntity.ok(category.getSubCategories().stream().map(SubCategoryResponse::from).collect(Collectors.toList()));
    }
    @GetMapping("/{categoryId}/subcategories/{subCategoryId}")
    public HttpEntity<?> get(@PathVariable ("categoryId") Long categoryId,@PathVariable("subCategoryId") Long subCategoryId){
        val category = categoryRepository.findById(categoryId).orElseThrow(NoSuchElementException::new);
        val subcategory = category.getSubCategories().stream().filter(subCategory -> subCategory.getId().equals (subCategoryId))
                .findFirst().orElseThrow(NoSuchElementException::new);
        return ResponseEntity.ok(SubCategoryResponse.from(subcategory));
    }
    @GetMapping
    public HttpEntity<List<CategoryResponse>> getAll(){
        val categorys=repository.findAll().stream().map(CategoryResponse::from).collect(Collectors.toList());
        return  ResponseEntity.ok(categorys);
    }
}
